import axios from 'axios'
import router from '../router/index'
import store from '../store/store'
import AuiDialog from '../assets/js/aui-dialog'
import AuiToast from '../assets/js/aui-toast'

/**
 * axios配置
 *
 */
axios.defaults.timeout = 10000
axios.defaults.headers.common['Content-Type'] = 'application/json'
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
axios.interceptors.request.use((reqConfig) => {
  let token = store.state.loginUserInfor.token
  let refreshToken = store.state.loginUserInfor.refreshToken
  if (token) {
    reqConfig.headers['Authorization'] = `Bearer ${token}`
    reqConfig.headers['x-refresh-token'] = `Bearer ${refreshToken}`
  }
  return reqConfig
}, {})
// 拦截响应response，并做一些错误处理
axios.interceptors.response.use((response) => {
  return response.data
}, (err) => {
  AuiToast.hide()
  AuiDialog.remove()
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        break
      case 401:
        err.message = '未授权，请登录'
        AuiDialog.alert({
          title: '错误提示',
          msg: '未授权，请登录',
          buttons: ['确定']
        }, function (ret) {
          if (ret.buttonIndex === 1) {
            store.state.loginUserInfor = {}
            localStorage.removeItem('loginUserInfor')
            router.replace({name: 'HelloWorld'})
            setTimeout(function () {
              location.reload()
            }, 200)
          }
        })
        return Promise.reject(err)
      case 403:
        err.message = '无权限！'
        break
      case 404:
        err.message = `请求地址出错`
        break
      case 408:
        err.message = '请求超时'
        break
      case 422:
        alert(err.response.data.message)
        break
      case 500:
        err.message = '服务器内部错误'
        break
      case 501:
        err.message = '服务未实现'
        break
      case 502:
        err.message = '网关错误'
        break
      case 503:
        err.message = '服务不可用'
        break
      case 504:
        err.message = '网关超时'
        break
      case 505:
        err.message = 'HTTP版本不受支持'
        break
      default:
    }
    AuiDialog.alert({
      title: '错误提示',
      msg: err.response.data.message,
      buttons: ['确定']
    }, function (ret) {
    })
  }
  return Promise.reject(err)
})
const http = {
}
export default http
